package com.dq.demo.model.http;

import android.content.Context;
import android.content.res.AssetManager;

import com.dq.demo.model.entity.BaseEntity;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Author : Z-JC
 * Date : 2020/1/12
 * Description :
 */
public class JsonUtil {

    /**
     * json串转实体类对象
     *
     * @param response
     * @param baseEntity
     * @return
     */
    public static <T> T fromJson(String response, BaseEntity baseEntity) {
        baseEntity = new Gson().fromJson(response, baseEntity.getClass());
        return (T) baseEntity;
    }

    /**
     * 解析单个Key
     *
     * @param response
     * @param key
     * @return
     */
    public static String parsingKey(String response, String key) {
        String value = "";
        try {
            JSONObject jsonObject = new JSONObject(response);
            value = jsonObject.getString(key);
        } catch (JSONException e) {
            e.printStackTrace();
            value = "";
        }
        return value;
    }

    /**
     * 解析单个Key
     *
     * @param response
     * @param key
     * @return
     */
    public static int parsKey(String response, String key) {
        int code = -1;
        try {
            JSONObject jsonObject = new JSONObject(response);
            code = jsonObject.getInt(key);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return code;
    }

    /**
     * 得到json文件中的内容
     *
     * @param context
     * @param fileName
     * @return
     */
    public static String getJsonString(Context context, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        //获得assets资源管理器
        AssetManager assetManager = context.getAssets();
        //使用IO流读取json文件内容
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName), "utf-8"));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
}